import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
import { Input, Switch, Space, Button } from 'antd';

interface Cell {
  rowSpan: number;
  colSpan: number;
  content: string;
}

interface TableGridProps {
  tableData: {
    rows: number;
    cols: number;
    cells: Cell[][];
  };
  selectedCells: { row: number; col: number }[];
  onSelectCells: (cells: { row: number; col: number }[]) => void;
  onUpdateCell: (row: number, col: number, content: string) => void;
}

const GridContainer = styled.div`
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  margin-top: 16px;
  overflow: auto;
  max-height: 600px;
  background-color: white;
`;

const ControlBar = styled.div`
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  padding: 8px;
  border-radius: 4px;
  border: 1px solid #d9d9d9;
`;

const Table = styled.table`
  border-collapse: collapse;
  width: 100%;
  table-layout: fixed;
`;

const TD = styled.td<{ isSelected: boolean; isSelecting: boolean }>`
  border: 1px solid #d9d9d9;
  padding: 8px;
  position: relative;
  background-color: ${(props) => {
    if (props.isSelecting) return '#ffccc7'; 
    return props.isSelected ? '#e6f7ff' : 'white';
  }};
  cursor: pointer;
  min-width: 100px;
  height: 40px;
  transition: all 0.2s;
  box-shadow: ${(props) => (props.isSelected ? 'inset 0 0 0 1px #1890ff' : 'none')};

  &:hover {
    background-color: ${(props) => {
      if (props.isSelecting) return '#ffccc7';
      return props.isSelected ? '#bae7ff' : '#f5f5f5';
    }};
  }
`;

const CellContent = styled.div`
  min-height: 20px;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
`;

const HelpText = styled.div`
  margin-top: 8px;
  margin-bottom: 8px;
  color: #888;
  font-size: 13px;
  background-color: #fafafa;
  padding: 8px;
  border-radius: 4px;
  border-left: 4px solid #1890ff;
`;

const TableGrid: React.FC<TableGridProps> = ({
  tableData,
  selectedCells,
  onSelectCells,
  onUpdateCell,
}) => {
  // 选择模式
  const [selectionMode, setSelectionMode] = useState<'row' | 'column' | 'cell'>('row');
  // 是否正在进行框选
  const [isSelecting, setIsSelecting] = useState(false);
  // 框选的起始单元格
  const [selectionStart, setSelectionStart] = useState<{row: number, col: number} | null>(null);
  // 当前鼠标停留的单元格（用于框选显示）
  const [hoverCell, setHoverCell] = useState<{row: number, col: number} | null>(null);
  
  // 清除选择
  const clearSelection = () => {
    onSelectCells([]);
    setSelectionStart(null);
    setHoverCell(null);
  };
  
  // 处理鼠标按下事件
  const handleMouseDown = (row: number, col: number, event: React.MouseEvent) => {
    if (event.button !== 0) return; // 只处理左键点击
    
    event.preventDefault();
    
    // 如果单元格是被合并的单元格的一部分（不可见），则不做任何操作
    if (tableData.cells[row][col].rowSpan === 0 || tableData.cells[row][col].colSpan === 0) {
      return;
    }
    
    // 如果按住Ctrl键，则切换该单元格的选中状态
    if (event.ctrlKey || event.metaKey) {
      const isAlreadySelected = selectedCells.some(
        (cell) => cell.row === row && cell.col === col
      );
      
      if (isAlreadySelected) {
        onSelectCells(
          selectedCells.filter((cell) => !(cell.row === row && cell.col === col))
        );
      } else {
        onSelectCells([...selectedCells, { row, col }]);
      }
      return;
    }
    
    // 否则，开始框选过程
    setIsSelecting(true);
    setSelectionStart({ row, col });
    onSelectCells([{ row, col }]);
  };
  
  // 处理鼠标移动事件
  const handleMouseMove = (row: number, col: number) => {
    // 更新鼠标悬停的单元格
    setHoverCell({ row, col });
    
    // 如果正在选择中，根据选择模式和起始点更新选择的单元格
    if (isSelecting && selectionStart) {
      let newSelection: {row: number, col: number}[] = [];
      
      if (selectionMode === 'row') {
        // 行选择模式：选择同一列上从起始行到当前行的所有单元格
        const startRow = Math.min(selectionStart.row, row);
        const endRow = Math.max(selectionStart.row, row);
        
        for (let r = startRow; r <= endRow; r++) {
          // 确保单元格不是被合并的隐藏单元格
          if (tableData.cells[r][selectionStart.col].rowSpan !== 0 && 
              tableData.cells[r][selectionStart.col].colSpan !== 0) {
            newSelection.push({ row: r, col: selectionStart.col });
          }
        }
      } else if (selectionMode === 'column') {
        // 列选择模式：选择同一行上从起始列到当前列的所有单元格
        const startCol = Math.min(selectionStart.col, col);
        const endCol = Math.max(selectionStart.col, col);
        
        for (let c = startCol; c <= endCol; c++) {
          // 确保单元格不是被合并的隐藏单元格
          if (tableData.cells[selectionStart.row][c].rowSpan !== 0 && 
              tableData.cells[selectionStart.row][c].colSpan !== 0) {
            newSelection.push({ row: selectionStart.row, col: c });
          }
        }
      } else {
        // 单元格选择模式：只选择当前单元格
        newSelection = [{ row: selectionStart.row, col: selectionStart.col }];
        
        // 检查当前单元格是否有效（不是被合并的隐藏单元格）
        if (tableData.cells[row][col].rowSpan !== 0 && 
            tableData.cells[row][col].colSpan !== 0) {
          newSelection = [selectionStart, { row, col }];
        }
      }
      
      onSelectCells(newSelection);
    }
  };
  
  // 处理鼠标抬起事件
  const handleMouseUp = () => {
    setIsSelecting(false);
  };
  
  // 处理单元格编辑
  const handleCellDoubleClick = (row: number, col: number) => {
    // 双击时，切换到编辑模式
    onSelectCells([{ row, col }]);
  };
  
  // 设置单元格内容
  const handleCellContentChange = (row: number, col: number, value: string) => {
    onUpdateCell(row, col, value);
  };
  
  // 检查单元格是否被选中
  const isCellSelected = (row: number, col: number) => {
    return selectedCells.some((cell) => cell.row === row && cell.col === col);
  };
  
  // 检查单元格是否在框选范围内
  const isCellInSelectionArea = (row: number, col: number) => {
    if (!isSelecting || !selectionStart || !hoverCell) return false;
    
    if (selectionMode === 'row') {
      // 行选择模式：单元格在同一列，且行在选择范围内
      if (col !== selectionStart.col) return false;
      
      const startRow = Math.min(selectionStart.row, hoverCell.row);
      const endRow = Math.max(selectionStart.row, hoverCell.row);
      return row >= startRow && row <= endRow;
    } else if (selectionMode === 'column') {
      // 列选择模式：单元格在同一行，且列在选择范围内
      if (row !== selectionStart.row) return false;
      
      const startCol = Math.min(selectionStart.col, hoverCell.col);
      const endCol = Math.max(selectionStart.col, hoverCell.col);
      return col >= startCol && col <= endCol;
    }
    
    return false;
  };
  
  // 在组件外部点击时清除选择
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as Element;
      if (!target.closest('table')) {
        // 如果点击的不是表格的一部分，则清除选择
        setIsSelecting(false);
      }
    };
    
    document.addEventListener('mouseup', handleMouseUp);
    document.addEventListener('click', handleClickOutside);
    
    return () => {
      document.removeEventListener('mouseup', handleMouseUp);
      document.removeEventListener('click', handleClickOutside);
    };
  }, []);
  
  // 渲染表格
  const renderTable = () => {
    const rows = [];
    for (let i = 0; i < tableData.rows; i++) {
      const cells = [];
      for (let j = 0; j < tableData.cols; j++) {
        const cell = tableData.cells[i][j];
        
        // 如果这个单元格被合并且不是合并的起始单元格，则跳过
        if (cell.rowSpan === 0 || cell.colSpan === 0) continue;
        
        cells.push(
          <TD
            key={`${i}-${j}`}
            rowSpan={cell.rowSpan}
            colSpan={cell.colSpan}
            isSelected={isCellSelected(i, j)}
            isSelecting={isCellInSelectionArea(i, j)}
            onMouseDown={(e) => handleMouseDown(i, j, e)}
            onMouseMove={() => handleMouseMove(i, j)}
            onDoubleClick={() => handleCellDoubleClick(i, j)}
          >
            <CellContent>
              {selectedCells.length === 1 && 
               selectedCells[0].row === i && 
               selectedCells[0].col === j ? (
                <Input
                  value={cell.content}
                  onChange={(e) => handleCellContentChange(i, j, e.target.value)}
                  autoFocus
                  onClick={(e) => e.stopPropagation()}
                />
              ) : (
                cell.content || <span style={{ color: '#ccc' }}>双击编辑</span>
              )}
            </CellContent>
          </TD>
        );
      }
      rows.push(<tr key={i}>{cells}</tr>);
    }
    return rows;
  };

  return (
    <>
      <ControlBar>
        <Space>
          <span>选择模式：</span>
          <Button 
            type={selectionMode === 'cell' ? 'primary' : 'default'} 
            onClick={() => setSelectionMode('cell')}
          >
            单元格
          </Button>
          <Button 
            type={selectionMode === 'row' ? 'primary' : 'default'} 
            onClick={() => setSelectionMode('row')}
          >
            行选择
          </Button>
          <Button 
            type={selectionMode === 'column' ? 'primary' : 'default'} 
            onClick={() => setSelectionMode('column')}
          >
            列选择
          </Button>
          <Button onClick={clearSelection}>清除选择</Button>
        </Space>
      </ControlBar>
      
      <HelpText>
        {selectionMode === 'row' && '当前模式：行选择 - 拖拽可选择同一列的多个单元格'}
        {selectionMode === 'column' && '当前模式：列选择 - 拖拽可选择同一行的多个单元格'}
        {selectionMode === 'cell' && '当前模式：单元格选择 - 点击选择单个单元格，按住Ctrl可选择多个单元格'}
      </HelpText>
      
      <GridContainer>
        <Table>
          <tbody>{renderTable()}</tbody>
        </Table>
      </GridContainer>
    </>
  );
};

export default TableGrid; 